import { h, Component } from 'preact';
import { observable, computed } from 'mobx';
import { observer } from 'mobx-react';

import { createDrag } from '../util/drag';
import { calcDistance } from '../util/geometry';

import Circle from '../basic-shape/Circle';
import Line from '../basic-shape/Line';

class Archor extends Component {
  constructor() {
    super();

    this.state = {
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0,
    }

    this.dragHandler = createDrag({
      onDragStart: this.onDragStart,
      onDraging: this.onDraging,
      onDragEnd: this.onDragEnd,
    });
  }

  isShowLine() {
    const v = calcDistance(
      { x: this.state.startX, y: this.state.startY },
      { x: this.state.endX, y: this.state.endY }
    );
    return v > 10;
  }

  onDragStart = () => {
    const { x, y } = this.props;
    this.setState({
      startX: x, startY: y,
      endX: x, endY: y,
    })
  }

  onDraging = ({ event, deltaX, deltaY }) => {
    const { endX, endY } = this.state;
    this.setState({
      endX: endX + deltaX, endY: endY + deltaY,
    })
  }

  onDragEnd = ({ event }) => {
    this.setState({
      startX: 0, startY: 0,
      endX: 0, endY: 0,
    })
  }

  render() {
    const { startX, startY, endX, endY } = this.state;
    const { x, y } = this.props;
    return (
      <g>
        <Circle
          {...{ x, y }}
          r="4"
          fill="#FFF"
          onMouseDown={this.dragHandler}
        />
        {this.isShowLine() && <Line
          x1={startX}
          y1={startY}
          x2={endX}
          y2={endY}
        />}
      </g>
    );
  }

};

export default Archor;
